"""
通用工具函数
"""
import json
from typing import Optional, Any
import re
        
def format_json_response(response):
    """
    清理并格式化LLM返回的JSON响应，支持对象{...}和数组[...]格式
    
    Args:
        response (str): LLM的原始响应文本
        
    Returns:
        str: 清理后的JSON字符串
    """
    # 1. 移除思考过程标签 <think>...</think>
    response = re.sub(r'<think>.*?</think>\s*', '', response, flags=re.DOTALL)
    
    # 2. 移除markdown代码块标记
    response = re.sub(r'```(?:json)?', '', response)
    
    # 3. 去除首尾空白
    response = response.strip()
    
    return response

def parse_llm_json_response(
    response: str,
    expected_type: Optional[type] = None,
    default_value: Any = None
) -> Any:
    """
    解析LLM返回的JSON格式响应
    
    Args:
        response: LLM的响应文本
        expected_type: 期望的返回类型（如list或dict），用于类型验证
        default_value: 解析失败时的默认返回值
        
    Returns:
        解析后的JSON数据，如果解析失败则返回default_value
        
    Examples:
        >>> # 解析列表
        >>> result = parse_llm_json_response(response, expected_type=list, default_value=[])
        >>> # 解析字典
        >>> result = parse_llm_json_response(response, expected_type=dict, default_value={})
    """
    try:
        json_str = format_json_response(response)

        print("清理后的json_str: ", json_str)
        # 3. 解析JSON
        result = json.loads(json_str)
        print("解析后的result: ", result)
        # 4. 类型验证
        if expected_type is not None and not isinstance(result, expected_type):
            print(f"类型不匹配: 期望 {expected_type.__name__}, 实际 {type(result).__name__}")
            return default_value
            
        return result
        
    except json.JSONDecodeError as e:
        print(f"JSON解析失败: {str(e)}")
        print(f"尝试解析的文本: {json_str}")
        return default_value
    except Exception as e:
        print(f"解析响应时出错: {str(e)}")
        return default_value